package my_service

import (
	"github.com/gin-gonic/gin"
	"github.com/kardianos/service"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
	"go.uber.org/zap"
	"log"
	"os"
	"virus-proxy/cmd/routes"
	//_ "virus-proxy/docs"
	"virus-proxy/internal/config"
	"virus-proxy/internal/logger"
	"virus-proxy/internal/mount"
	"virus-proxy/internal/vendor_api/client"
)

//var (
//	kernel32DLL       = syscall.NewLazyDLL("kernel32.dll")
//	outputDebugString = kernel32DLL.NewProc("OutputDebugStringW")
//)
//
//func OutputDebugString(message string) {
//	strPtr, _ := syscall.UTF16PtrFromString(message)
//	outputDebugString.Call(uintptr(unsafe.Pointer(strPtr)))
//}

// my_service.go:将程序封装成windows服务

// MyService 实现了 service.Service 接口
type MyService struct {
	exit chan struct{} // 用于服务停止时的通知
}

func (m *MyService) Start(s service.Service) error {
	m.exit = make(chan struct{})
	go m.run()
	return nil
}

func (m *MyService) run() {
	//OutputDebugString("Service starting...")
	//ex, err := os.Executable()
	//if err != nil {
	//	//OutputDebugString("Error find current directory " + err.Error())
	//	log.Fatalf("Error find current directory %v", err)
	//}
	//exPath := filepath.Dir(ex)

	// 加载配置文件
	//cfg, err := config.LoadConfig(filepath.Join(exPath, "config.json"))
	mount.InitDO("", "")
	cfg, err := config.LoadConfig("config.json")
	if err != nil {
		//OutputDebugString("Error loading config: " + err.Error())
		log.Fatalf("Error loading config: %v", err)
	}

	// 初始化
	logger.InitLogger(cfg.LogLevel)
	err = mount.UpdateMount()
	if err != nil {
		logger.LogError("Failed to init mount array.", zap.Error(err))
		//OutputDebugString("Failed to init mount array.")
		os.Exit(1)
	}

	// 启动Gin Web服务
	gin.SetMode(gin.ReleaseMode)
	r := gin.New()
	r.Use(logger.GinLogger(), logger.GinRecovery(true))

	// 监听NAS请求，创建代理
	proxy := client.NewProxy(cfg.ControlCenterIP, cfg.ControlCenterPort, cfg.Vendor, cfg.SecretID, cfg.SecretKey)

	// 挂载设备路径
	r.POST("/mountPoint", routes.MountPoint())
	// 执行扫描任务
	r.POST("/scan", routes.ScanTask(proxy))
	//r.POST("/scanQAX", routes.ScanQAX())
	r.POST("/list", routes.ListMountPoint())
	r.POST("/unMount", routes.UnMountPoint())
	r.POST("/realTimeScan", routes.ScanRealTimeTask(proxy))
	//添加swagger访问路由
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	// 启动Gin服务器（非阻塞方式运行）
	go func() {
		err = r.Run(":" + cfg.Port)
		if err != nil {
			logger.LogError("Failed to start server.", zap.Error(err))
			//OutputDebugString("Failed to start server: " + err.Error())
			close(m.exit)
		}
	}()

	// 等待服务停止信号
	<-m.exit
	//OutputDebugString("Service stopping...")
}

func (m *MyService) Stop(s service.Service) error {
	// 停止服务的逻辑
	//OutputDebugString("Service exit signal received.")
	close(m.exit) // 通知服务停止
	return nil
}
